<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row>
        <el-col
          ><el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          ></el-col
        >
      </el-row>
      <!-- 表格区 -->
      <tree-table
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        show-index
        index-text="#"
        stripe
        border
        :expand-type="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            style="color: green"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- options用来指定数据源parentCateList -->
          <el-cascader
            v-model="cateKeys"
            :props="cascaderProps"
            :options="parentCateList"
            @change="parentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类的对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "myCate",
  data() {
    return {
      catelist: [],
      queryinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
          minWidth: "130px",
        },
      ],
      addCateDialogVisible: false, //添加分类的对话框显示与隐藏
      editDialogVisible: false, //编辑分类的对话框显示与隐藏
      addCateForm: {
        cat_name: "", //分类名称
        cat_pid: 0, //父级分类的id
        cat_level: 0, //默认添加一级分类
      },
      //添加分类的验证
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      //编辑分类的数据
      editCateForm: {
        cat_deleted: "fasle",
        cat_id: "",
        cat_name: "",
        cat_pid: "",
        cat_level: "",
      },
      //编辑分类的验证
      editCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      parentCateList: [], //父级分类
      cateKeys: [], //所选择的分类id 数组
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true,
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryinfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取分类列表失败！");
      this.catelist = res.data.result;
      this.total = res.data.total;
      // console.log(res.data);
    },
    handleSizeChange(newSize) {
      this.queryinfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.queryinfo.pagenum = newPage;
      this.getCateList();
    },
    //获取分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类失败！");
      this.parentCateList = res.data;
    },
    //点击添加分类按钮
    showAddCateDialog() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //级联选择的数据发生变化
    parentCateChange() {
      console.log(this.cateKeys);
      //如果cateKeys的数组长度大于0，说明有选择数据分类
      if (this.cateKeys.length > 0) {
        this.addCateForm.cat_pid = this.cateKeys[this.cateKeys.length - 1];
        this.addCateForm.cat_level = this.cateKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },
    //点击按钮，添加分类
    addCate() {
      // console.log(this.addCateForm);
      // 发起请求之前先验证表单
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败！");
        this.$message.success("添加成功！");
        this.addCateDialogVisible = false;
        this.getCateList();
      });
      // console.log(res);
    },
    //监听添加分类对话框的关闭事件
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.cateKeys = 0;
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //编辑分类
    async editCate(id) {
      //根据id获取分类信息
      const { data: res } = await this.$http.get("categories/" + id);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取分类失败！");
      this.editCateForm = res.data;
      //获取成功后显示对话框
      this.editDialogVisible = true;
    },
    submitEditCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          this.editCateForm
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败！");
        this.$message.success("更新成功！");
        this.getCateList();
        this.editDialogVisible = false;
      });
    },
    //删除分类
    async deleteCate(id) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result === "confirm") {
        const { data: res } = await this.$http.delete("categories/" + id);
        if (res.meta.status !== 200) return this.$message.error("删除失败！");
        this.$message.success("删除成功！");
        this.getCateList();
      } else {
        return this.$message.info("已取消删除！");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-button {
  margin-bottom: 15px;
}
.el-pagination {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>